// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <re2/re2.h>

#include <pollux/common/config/config.h>
#include <pollux/core/query_config.h>
#include <pollux/type/tz/time_zone_map.h>

namespace kumo::pollux::core {
    QueryConfig::QueryConfig(
        const std::unordered_map<std::string, std::string> &values)
        : config_{
            std::make_unique<config::ConfigBase>(
                std::unordered_map<std::string, std::string>(values))
        } {
        validateConfig();
    }

    QueryConfig::QueryConfig(std::unordered_map<std::string, std::string> &&values)
        : config_{std::make_unique<config::ConfigBase>(std::move(values))} {
        validateConfig();
    }

    void QueryConfig::validateConfig() {
        // Validate if timezone name can be recognized.
        if (config_->valueExists(QueryConfig::kSessionTimezone)) {
            POLLUX_USER_CHECK(
                tz::getTimeZoneID(
                    config_->get<std::string>(QueryConfig::kSessionTimezone).value(),
                    false) != -1,
                fmt::format(
                    "session '{}' set with invalid value '{}'",
                    QueryConfig::kSessionTimezone,
                    config_->get<std::string>(QueryConfig::kSessionTimezone).value()));
        }
    }

    void QueryConfig::testingOverrideConfigUnsafe(
        std::unordered_map<std::string, std::string> &&values) {
        config_ = std::make_unique<config::ConfigBase>(std::move(values));
    }

    std::unordered_map<std::string, std::string> QueryConfig::rawConfigsCopy()
    const {
        return config_->rawConfigsCopy();
    }
} // namespace kumo::pollux::core
